<template>
  <div class="register-page">
    <div class="register-container">
      <!-- 左侧装饰图片 -->
      <div class="register-banner">
        <div class="banner-content">
          <h1 class="gradient-text">加入我们</h1>
          <p>开启你的美好生活分享之旅</p>
          <div class="features">
            <div class="feature-item">
              <el-icon><Edit /></el-icon>
              <span>创作内容</span>
            </div>
            <div class="feature-item">
              <el-icon><User /></el-icon>
              <span>结识朋友</span>
            </div>
            <div class="feature-item">
              <el-icon><Trophy /></el-icon>
              <span>获得认可</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧注册表单 -->
      <div class="register-form-container">
        <div class="register-form">
          <div class="form-header">
            <h2>创建新账号</h2>
            <p>加入小红书，发现更多精彩内容</p>
          </div>
          
          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            label-position="top"
            class="register-form-content"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                size="large"
                class="form-input"
                @blur="checkUsernameAvailable"
                :prefix-icon="User"
              >
                <template #suffix v-if="usernameChecking">
                  <el-icon class="is-loading"><Loading /></el-icon>
                </template>
              </el-input>
              <div v-if="usernameStatus" class="username-status" :class="usernameStatus.type">
                {{ usernameStatus.message }}
              </div>
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="registerForm.email"
                placeholder="请输入邮箱地址"
                size="large"
                class="form-input"
                type="email"
              >
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="昵称" prop="nickname">
              <el-input
                v-model="registerForm.nickname"
                placeholder="请输入昵称（可选）"
                size="large"
                class="form-input"
              >
                <template #prefix>
                  <el-icon><Avatar /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                class="form-input"
                show-password
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                size="large"
                class="form-input"
                show-password
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <div class="form-agreement">
              <el-checkbox v-model="agreedToTerms" size="large">
                我已阅读并同意
                <el-link type="primary">《用户协议》</el-link>
                和
                <el-link type="primary">《隐私政策》</el-link>
              </el-checkbox>
            </div>
            
            <el-button
              type="primary"
              size="large"
              class="register-button"
              :loading="loading"
              :disabled="!agreedToTerms"
              @click="handleRegister"
            >
              {{ loading ? '注册中...' : '注册' }}
            </el-button>
            
            <div class="form-footer">
              <span>已有账号？</span>
              <el-link type="primary" @click="$router.push('/login')">
                立即登录
              </el-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { checkUsername } from '@/api/auth'
import { ElMessage } from 'element-plus'
import { 
  User, 
  Lock, 
  Message, 
  Avatar,
  Edit, 
  Trophy,
  Loading
} from '@element-plus/icons-vue'

const authStore = useAuthStore()

const registerFormRef = ref()
const loading = ref(false)
const agreedToTerms = ref(false)
const usernameChecking = ref(false)
const usernameStatus = ref(null)

const registerForm = reactive({
  username: '',
  email: '',
  nickname: '',
  password: '',
  confirmPassword: ''
})

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 检查用户名是否可用
const checkUsernameAvailable = async () => {
  if (!registerForm.username || registerForm.username.length < 3) {
    usernameStatus.value = null
    return
  }
  
  usernameChecking.value = true
  usernameStatus.value = null
  
  try {
    const res = await checkUsername(registerForm.username)
    if (res.data) {
      usernameStatus.value = {
        type: 'success',
        message: '用户名可用'
      }
    } else {
      usernameStatus.value = {
        type: 'error',
        message: '用户名已被占用'
      }
    }
  } catch (error) {
    usernameStatus.value = {
      type: 'error',
      message: '检查用户名失败'
    }
  } finally {
    usernameChecking.value = false
  }
}

const handleRegister = async () => {
  console.log('🔍 注册按钮被点击了')
  console.log('🔍 registerFormRef.value:', registerFormRef.value)
  console.log('🔍 registerFormRef本身:', registerFormRef)
  
  // 如果第一次检查为空，等待一下再检查
  if (!registerFormRef.value) {
    console.log('❌ registerFormRef 为空，等待100ms后重试...')
    await new Promise(resolve => setTimeout(resolve, 100))
    console.log('🔍 重试后 registerFormRef.value:', registerFormRef.value)
  }
  
  if (!registerFormRef.value) {
    console.log('❌ registerFormRef 仍然为空，直接返回')
    ElMessage.error('表单初始化失败，请刷新页面重试')
    return
  }
  
  try {
    console.log('🔍 开始表单验证...')
    const valid = await registerFormRef.value.validate()
    console.log('🔍 表单验证结果:', valid)
    
    if (!valid) {
      console.log('❌ 表单验证失败')
      return
    }
    
    if (usernameStatus.value?.type === 'error') {
      ElMessage.error('请先解决用户名问题')
      return
    }
    
    console.log('🔍 表单验证通过，开始注册...')
    console.log('🔍 注册表单数据:', registerForm)
    
    loading.value = true
    await authStore.register(registerForm)
    
    console.log('✅ 注册处理完成')
  } catch (error) {
    console.error('❌ 注册失败:', error)
  } finally {
    loading.value = false
    console.log('🔍 重置loading状态')
  }
}
</script>

<style scoped lang="scss">
.register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, $secondary-color 0%, $bg-white 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: $spacing-lg;
}

.register-container {
  max-width: 1000px;
  width: 100%;
  background: $bg-white;
  border-radius: $border-radius-large;
  box-shadow: $shadow-heavy;
  overflow: hidden;
  display: grid;
  grid-template-columns: 1fr 1fr;
  min-height: 700px;
}

.register-banner {
  background: linear-gradient(135deg, $primary-color 0%, $primary-light 100%);
  color: $text-white;
  padding: $spacing-xxl;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .banner-content {
    text-align: center;
    
    h1 {
      font-size: $font-size-xxl * 1.5;
      margin-bottom: $spacing-md;
      background: linear-gradient(135deg, $text-white 0%, rgba(255, 255, 255, 0.8) 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
    
    p {
      font-size: $font-size-lg;
      margin-bottom: $spacing-xl;
      opacity: 0.9;
    }
    
    .features {
      display: flex;
      flex-direction: column;
      gap: $spacing-lg;
      
      .feature-item {
        display: flex;
        align-items: center;
        gap: $spacing-md;
        font-size: $font-size-md;
        
        .el-icon {
          font-size: $font-size-lg;
        }
      }
    }
  }
}

.register-form-container {
  padding: $spacing-xxl;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow-y: auto;
}

.register-form {
  width: 100%;
  max-width: 350px;
  
  .form-header {
    text-align: center;
    margin-bottom: $spacing-lg;
    
    h2 {
      color: $text-primary;
      font-size: $font-size-xxl;
      margin-bottom: $spacing-sm;
    }
    
    p {
      color: $text-secondary;
      font-size: $font-size-sm;
    }
  }
  
  .register-form-content {
    .form-input {
      :deep(.el-input__wrapper) {
        border-radius: $border-radius-medium;
      }
    }
    
    .username-status {
      font-size: $font-size-xs;
      margin-top: $spacing-xs;
      
      &.success {
        color: $success-color;
      }
      
      &.error {
        color: $error-color;
      }
    }
    
    .form-agreement {
      margin-bottom: $spacing-lg;
      
      :deep(.el-checkbox__label) {
        font-size: $font-size-sm;
        color: $text-secondary;
      }
    }
    
    .register-button {
      width: 100%;
      border-radius: $border-radius-medium;
      background: linear-gradient(135deg, $primary-color 0%, $primary-light 100%);
      border: none;
      margin-bottom: $spacing-lg;
      
      &:hover:not(:disabled) {
        background: linear-gradient(135deg, $primary-dark 0%, $primary-color 100%);
      }
      
      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }
    }
    
    .form-footer {
      text-align: center;
      color: $text-secondary;
      
      .el-link {
        margin-left: $spacing-xs;
      }
    }
  }
}

// 响应式设计
@media (max-width: $breakpoint-md) {
  .register-container {
    grid-template-columns: 1fr;
    max-width: 400px;
  }
  
  .register-banner {
    display: none;
  }
  
  .register-form-container {
    padding: $spacing-xl;
  }
}

@media (max-width: $breakpoint-sm) {
  .register-page {
    padding: $spacing-md;
  }
  
  .register-form-container {
    padding: $spacing-lg;
  }
  
  .register-banner {
    .banner-content {
      .features {
        gap: $spacing-md;
        
        .feature-item {
          font-size: $font-size-sm;
        }
      }
    }
  }
}
</style> 